package com.simoniu.batchdemo;

import com.simoniu.entity.Students;
import com.simoniu.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class BatchDemo {

    //使用Statement语句执行一个批处理
    public void executeBatchWithStatement() {
        //适合执行语句类型不同的批处理。
        String sql = "";
        try (Connection conn = DBUtil.getConnection()
             ; Statement stmt = conn.createStatement()) {
            sql = "insert into students (sname,gender) values ('曹操','男')";
            stmt.addBatch(sql);
            sql = "update students set gender = '女' where sid = 7";
            stmt.addBatch(sql);
            sql = "delete from students where sid >8";
            stmt.addBatch(sql);
            //执行批处理
            stmt.executeBatch();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //使用PreparedStatement执行一个批处理
    public void executeBatchWithPreparedStatement(List<Students> studentsList) {
        String sql = "insert into students (sname,gender) values (?,?)";
        try (Connection conn = DBUtil.getConnection()
             ; PreparedStatement pstmt = conn.prepareStatement(sql)) {
            studentsList.forEach(s -> {
                try {
                    pstmt.setString(1, s.getSname());
                    pstmt.setString(2, s.getGender());
                    pstmt.addBatch();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
            pstmt.executeBatch();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        List<Students> studentsList = new ArrayList<Students>();

        for (int i = 10; i <= 20; i++) {
            Students s = new Students(110, "张" + i, "男");
            studentsList.add(s);
        }

        BatchDemo demo = new BatchDemo();
        //demo.executeBatchWithStatement();
        demo.executeBatchWithPreparedStatement(studentsList);
    }
}
